package com.example.flow.pipeline.model.result;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;

/**
 * @Desprication: 封装返回值的实体类
 * @Author: YangBin
 * @Date: created in 11:09 2020/2/23
 * @Modify By:
 */
@Data
@AllArgsConstructor
public class FlowResult<T> implements Serializable {

    @JSONField(serialize = false)
    boolean success;
    int code;
    String message;
    T data;

    public static <T> FlowResult<T> ok() {
        return succeedWith(null, FlowResultCode.SUCCESS.getName());
    }

    public static <T> FlowResult<T> ok(T data) {
        return succeedWith(data, FlowResultCode.SUCCESS.getName());
    }

    public static <T> FlowResult<T> ok(T data, String message) {
        return succeedWith(data, message);
    }

    private static <T> FlowResult<T> succeedWith(T data, String message) {
        return new FlowResult<>(true, FlowResultCode.SUCCESS.getCode(), message, data);
    }

    public static <T> FlowResult<T> fail(FlowResultCode flowResultCode) {
        return failedWith(flowResultCode, FlowResultCode.FAIL.getName(), null);
    }

    public static <T> FlowResult<T> fail(FlowResultCode flowResultCode, String message) {
        return failedWith(flowResultCode, message, null);
    }

    public static <T> FlowResult<T> fail() {
        return failedWith(FlowResultCode.FAIL, FlowResultCode.FAIL.getName(), null);
    }

    public static <T> FlowResult<T> fail(String message) {
        return failedWith(FlowResultCode.FAIL, message, null);
    }

    public static <T> FlowResult<T> fail(T data) {
        return failedWith(FlowResultCode.FAIL, FlowResultCode.FAIL.getName(), data);
    }

    public static <T> FlowResult<T> fail(String message, T data) {
        return failedWith(FlowResultCode.FAIL, FlowResultCode.FAIL.getName(), data);
    }

    private static <T> FlowResult<T> failedWith(FlowResultCode flowResultCode, String message, T data) {
        return new FlowResult<>(false, flowResultCode.getCode(), message, data);
    }

}
